#include "linux_def.h"
#include "core.h"

#define TIME_SLOTS	64

static int	slot;
static int	time_lock;

volatile uintptr_t current_msec;
volatile g_time_t *g_cached_time;
static g_time_t cached_time[TIME_SLOTS];

void time_init()
{
	g_cached_time = &cached_time[0];

	tzset();
	
	time_update(0, 0);
}

void time_update(time_t sec, int msec)
{
	struct tm tm, gmt;
	g_time_t *tp;
	struct timeval tv;

	if (!trylock(&time_lock))
		return;

	if (sec == 0){
		gettimeofday(&tv, NULL);
		sec = tv.tv_sec;	//秒
		msec = tv.tv_usec / 1000;	//毫秒
	}

	//当前时间以毫秒计量, 同时放在树中使用
	current_msec = (uintptr_t)sec * 1000 + msec;
	
	tp = &cached_time[slot];

	if (tp->sec == sec){
		tp->msec = msec;
		unlock(&time_lock);	
		return;
	}

	if (slot = TIME_SLOTS - 1)	//达到最大树高度
		slot = 0;
	else
		slot++;

	tp = &cached_time[slot];
	tp->sec = sec;
	tp->msec = msec;

	g_cached_time = tp;
	unlock(&time_lock);
}

